package com.mmsj;

import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author ChuXuan
 */
public class MainActivity extends AppCompatActivity {

//    定义组件
    EditText editText;
    Button button;
    Button button2;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取组件
        editText = findViewById(R.id.editText);
        button = findViewById(R.id.button);
        button2 = findViewById(R.id.button2);
        textView = findViewById(R.id.textView);

        //绑定事件
        button.setOnClickListener(v -> {
            //获取组件的文本
            String text = editText.getText().toString()+"\r\n";
            // 创建或打开文件
           try {
//                追加
               FileOutputStream fos = openFileOutput("myFile.txt", Context.MODE_APPEND);
               fos.write(text.getBytes());
               fos.flush();
               fos.close();
               Toast.makeText(MainActivity.this, "文件保存成功", Toast.LENGTH_SHORT).show();
           } catch (Exception e) {
               e.printStackTrace();
           }
        });
        button2.setOnClickListener(v -> {
            // 读取文件内容
            try {
                FileInputStream fis = openFileInput("myFile.txt");
                byte[] buffer = new byte[fis.available()];
            // 写入文件内容 -> 显示到textView上
                if(fis.read(buffer) != -1) {
                    textView.setText(new String(buffer));
                }
                fis.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


}